import { defineStore } from 'pinia'
import { computed, reactive, ref, watch, toRaw } from 'vue'

const STORAGE_KEY = 'ai_agent_configs'
const ACTIVE_STORAGE_KEY = 'ai_active_agent'
const HISTORY_LIMIT = 20

const defaultFeatureToggles = () => ({
  enableVoiceInput: true,
  enableMarkdown: true,
  enableCodeHighlight: true,
  enableReasoning: true,
  autoScroll: true
})

const generateId = () => {
  const random = Math.random().toString(16).slice(2, 10)
  return `agent_${Date.now().toString(36)}_${random}`
}

const deepClone = (value) => {
  const rawValue = toRaw(value)
  if (typeof structuredClone === 'function') {
    try {
      return structuredClone(rawValue)
    } catch (error) {
      console.warn('[AgentStore] structuredClone 失败，使用兼容深拷贝', error)
    }
  }
  const visited = new WeakMap()
  const cloneRecursive = (val) => {
    if (val === null || typeof val !== 'object') {
      return val
    }
    if (visited.has(val)) {
      return visited.get(val)
    }
    if (Array.isArray(val)) {
      const arr = []
      visited.set(val, arr)
      val.forEach((item) => {
        arr.push(cloneRecursive(item))
      })
      return arr
    }
    const obj = {}
    visited.set(val, obj)
    Object.keys(val).forEach((key) => {
      obj[key] = cloneRecursive(val[key])
    })
    return obj
  }
  return cloneRecursive(rawValue)
}

const createHistoryEntry = (agentSnapshot, note = '', type = 'update') => ({
  id: generateId(),
  version: agentSnapshot.version?.current ?? 1,
  timestamp: Date.now(),
  note,
  type,
  status: agentSnapshot.status,
  snapshot: deepClone(agentSnapshot)
})

const createBlankAgent = (overrides = {}) => {
  const timestamp = Date.now()
  const baseAgent = {
    id: generateId(),
    name: '通用智能体',
    description: '适用于常规问答与办公助手场景的通用智能体配置',
    avatar: '',
    tags: ['默认'],
    status: 'published',
    prompt: {
      system: '你是一个专业的企业数字助手，需根据用户问题提供准确、可靠且可执行的回答。',
      styleGuide: '语气专业、友好，回答结构化，必要时给出步骤或清单。',
      refusalPolicy: '当问题涉及违法、侵权或不在能力范围内时，应礼貌拒绝并给出合理解释。',
      openingMessage: '您好！我是企业智能助理，可以为您提供业务咨询、报表分析与系统操作指导。',
      memoryStrategy: 'summary'
    },
    llm: {
      provider: 'openai',
      model: 'gpt-4.1-mini',
      endpoint: '',
      sseUrl: '',
      apiKeyAlias: '',
      temperature: 0.7,
      top_p: 0.95,
      top_k: 40,
      frequency_penalty: 0,
      presence_penalty: 0,
      max_tokens: 2048,
      response_format: 'auto',
      stop: []
    },
    context: {
      enableMemory: true,
      memoryType: 'summary',
      conversationWindow: 20,
      summaryInterval: 5,
      forgetRules: [],
      memoryRetention: '7d'
    },
    capabilities: {
      tools: [],
      knowledgeBases: [],
      workflows: [],
      allowFileUpload: true,
      allowWebAccess: false,
      allowPluginExecution: true
    },
    compliance: {
      sensitiveWordListId: '',
      auditLevel: 'standard',
      autoRedact: false,
      disclaimers: ''
    },
    limits: {
      dailyRequests: 1000,
      perUserRequests: 200,
      tokenBudget: 200000,
      concurrency: 3,
      alertThreshold: 0.8
    },
    monitoring: {
      enableMetrics: true,
      latencyThreshold: 5000,
      errorAlertThreshold: 0.1,
      notifyEmails: []
    },
    featureToggles: defaultFeatureToggles(),
    version: {
      current: 1,
      published: 1,
      history: []
    },
    createdBy: 'local',
    createdAt: timestamp,
    updatedAt: timestamp,
    publishedAt: timestamp
  }
  return Object.assign(baseAgent, deepClone(overrides || {}))
}

const mergeDeep = (target, source) => {
  if (!source || typeof source !== 'object') return target
  Object.keys(source).forEach((key) => {
    const sourceValue = source[key]
    const targetValue = target[key]
    if (Array.isArray(sourceValue)) {
      target[key] = deepClone(sourceValue)
    } else if (sourceValue && typeof sourceValue === 'object') {
      target[key] = mergeDeep(
        targetValue && typeof targetValue === 'object' ? targetValue : {},
        sourceValue
      )
    } else {
      target[key] = sourceValue
    }
  })
  return target
}

const mapAgentToLegacySettings = (agent) => {
  if (!agent) return null
  return {
    agentId: agent.id,
    agentName: agent.name,
    description: agent.description,
    tags: agent.tags,
    aiModel: agent.llm?.model ?? '',
    aiProvider: agent.llm?.provider ?? '',
    aiUrl: agent.llm?.endpoint ?? '',
    sseUrl: agent.llm?.sseUrl ?? '',
    apiKeyAlias: agent.llm?.apiKeyAlias ?? '',
    temperature: agent.llm?.temperature ?? 0.7,
    topP: agent.llm?.top_p ?? 1,
    topK: agent.llm?.top_k ?? 0,
    maxTokens: agent.llm?.max_tokens ?? 2048,
    presencePenalty: agent.llm?.presence_penalty ?? 0,
    frequencyPenalty: agent.llm?.frequency_penalty ?? 0,
    responseFormat: agent.llm?.response_format ?? 'auto',
    systemPrompt: agent.prompt?.system ?? '',
    styleGuide: agent.prompt?.styleGuide ?? '',
    refusalPolicy: agent.prompt?.refusalPolicy ?? '',
    openingMessage: agent.prompt?.openingMessage ?? '',
    memoryStrategy: agent.prompt?.memoryStrategy ?? 'summary',
    enableVoiceInput: agent.featureToggles?.enableVoiceInput ?? true,
    enableMarkdown: agent.featureToggles?.enableMarkdown ?? true,
    enableCodeHighlight: agent.featureToggles?.enableCodeHighlight ?? true,
    enableReasoning: agent.featureToggles?.enableReasoning ?? true,
    autoScroll: agent.featureToggles?.autoScroll ?? true,
    tools: agent.capabilities?.tools ?? [],
    knowledgeBases: agent.capabilities?.knowledgeBases ?? [],
    workflows: agent.capabilities?.workflows ?? [],
    contextWindow: agent.context?.conversationWindow ?? 20,
    summaryInterval: agent.context?.summaryInterval ?? 5,
    forgetRules: agent.context?.forgetRules ?? []
  }
}

const persistJson = (key, value) => {
  if (typeof window === 'undefined') return
  try {
    const plain = deepClone(value)
    localStorage.setItem(key, JSON.stringify(plain))
  } catch (error) {
    console.error('[AgentStore] 保存本地配置失败', error)
  }
}

const restoreJson = (key, fallback) => {
  if (typeof window === 'undefined') return deepClone(fallback)
  try {
    const saved = localStorage.getItem(key)
    if (saved) {
      return JSON.parse(saved)
    }
  } catch (error) {
    console.error('[AgentStore] 读取本地配置失败', error)
  }
  return deepClone(fallback)
}

export const useAgentStore = defineStore('agent', () => {
  const agents = ref([])
  const activeAgentId = ref(null)
  const initialized = ref(false)
  const loading = ref(false)

  const initialize = () => {
    if (initialized.value) return
    initialized.value = true

    const restoredAgents = restoreJson(STORAGE_KEY, null)
    if (Array.isArray(restoredAgents) && restoredAgents.length > 0) {
      agents.value = restoredAgents.map((agent) => {
        const merged = mergeDeep(createBlankAgent(), agent)
        merged.featureToggles = Object.assign(
          defaultFeatureToggles(),
          agent.featureToggles || {}
        )
        return merged
      })
    } else {
      const defaultAgent = createBlankAgent()
      defaultAgent.version.history = [
        createHistoryEntry(defaultAgent, '初始创建', 'create')
      ]
      agents.value = [defaultAgent]
    }

    const restoredActiveId = restoreJson(ACTIVE_STORAGE_KEY, null)
    if (restoredActiveId && agents.value.some((a) => a.id === restoredActiveId)) {
      activeAgentId.value = restoredActiveId
    } else {
      activeAgentId.value = agents.value[0]?.id ?? null
    }
    syncActiveAgentToLegacySettings()
  }

  const syncActiveAgentToLegacySettings = () => {
    if (typeof window === 'undefined') return
    const data = mapAgentToLegacySettings(activeAgent.value)
    if (data) {
      persistJson('aiSettings', data)
    }
  }

  const persistState = () => {
    persistJson(STORAGE_KEY, agents.value)
    persistJson(ACTIVE_STORAGE_KEY, activeAgentId.value)
  }

  const activeAgent = computed(() =>
    agents.value.find((item) => item.id === activeAgentId.value) || null
  )

  const publishedAgents = computed(() =>
    agents.value.filter((agent) => agent.status === 'published')
  )

  const draftAgents = computed(() =>
    agents.value.filter((agent) => agent.status !== 'published')
  )

  const selectAgent = (agentId) => {
    if (!agentId || !agents.value.some((agent) => agent.id === agentId)) return
    activeAgentId.value = agentId
    syncActiveAgentToLegacySettings()
    persistState()
  }

  const createAgent = (payload = {}) => {
    const agent = createBlankAgent(payload)
    agent.status = payload.status ?? 'draft'
    agent.version = {
      current: 1,
      published: agent.status === 'published' ? 1 : 0,
      history: [createHistoryEntry(agent, '创建', 'create')]
    }
    agents.value.unshift(agent)
    activeAgentId.value = agent.id
    persistState()
    syncActiveAgentToLegacySettings()
    return agent
  }

  const updateAgent = (agentId, updates, options = {}) => {
    const index = agents.value.findIndex((agent) => agent.id === agentId)
    if (index === -1) return null

    const agent = deepClone(agents.value[index])
    const snapshot = deepClone(agents.value[index])

    const { mergeStrategy = 'merge', note = '配置更新', type = 'update', skipHistory = false } = options

    let nextAgent
    if (mergeStrategy === 'replace') {
      nextAgent = deepClone(updates)
      nextAgent.id = agentId
    } else {
      nextAgent = mergeDeep(agent, updates)
    }

    nextAgent.updatedAt = Date.now()
    nextAgent.version = nextAgent.version || {
      current: 1,
      published: agent.version?.published ?? 0,
      history: agent.version?.history ?? []
    }
    nextAgent.version.current = (agent.version?.current ?? 1) + 1

    if (!skipHistory) {
      const historyEntry = createHistoryEntry(snapshot, note, type)
      nextAgent.version.history = [
        historyEntry,
        ...(agent.version?.history ?? [])
      ].slice(0, HISTORY_LIMIT)
    }

    agents.value.splice(index, 1, nextAgent)
    persistState()
    if (activeAgentId.value === agentId) {
      syncActiveAgentToLegacySettings()
    }
    return nextAgent
  }

  const publishAgent = (agentId, note = '发布新版本') => {
    const agent = agents.value.find((item) => item.id === agentId)
    if (!agent) return null
    const nextVersion = (agent.version?.current ?? 1) + 1
    return updateAgent(
      agentId,
      {
        status: 'published',
        publishedAt: Date.now(),
        version: {
          ...(agent.version || {}),
          published: nextVersion
        }
      },
      {
        note,
        type: 'publish'
      }
    )
  }

  const deleteAgent = (agentId) => {
    const index = agents.value.findIndex((agent) => agent.id === agentId)
    if (index === -1) return
    agents.value.splice(index, 1)

    if (agents.value.length === 0) {
      const fallback = createBlankAgent()
      fallback.version.history = [
        createHistoryEntry(fallback, '创建', 'create')
      ]
      agents.value.push(fallback)
      activeAgentId.value = fallback.id
    } else if (activeAgentId.value === agentId) {
      activeAgentId.value = agents.value[0].id
    }

    persistState()
    syncActiveAgentToLegacySettings()
  }

  const cloneAgent = (agentId) => {
    const source = agents.value.find((agent) => agent.id === agentId)
    if (!source) return null
    const cloned = deepClone(source)
    cloned.id = generateId()
    cloned.name = `${source.name} 副本`
    cloned.status = 'draft'
    cloned.createdAt = Date.now()
    cloned.updatedAt = Date.now()
    cloned.version = {
      current: 1,
      published: 0,
      history: [createHistoryEntry(cloned, `从 ${source.name} 复制`, 'clone')]
    }
    agents.value.unshift(cloned)
    activeAgentId.value = cloned.id
    persistState()
    return cloned
  }

  const upsertCapabilityOption = (agentId, key, values) => {
    if (!Array.isArray(values)) return null
    return updateAgent(
      agentId,
      {
        capabilities: {
          [key]: [...values]
        }
      },
      {
        note: `更新${key}配置`,
        type: 'capability'
      }
    )
  }

  const registerVersionSnapshot = (agentId, snapshot, note = '版本快照') => {
    if (!snapshot) return null
    return updateAgent(
      agentId,
      {
        version: {
          history: [createHistoryEntry(snapshot, note, 'snapshot')]
        }
      },
      { skipHistory: true }
    )
  }

  const restoreVersion = (agentId, snapshotId, note = '回滚版本') => {
    const agent = agents.value.find((item) => item.id === agentId)
    if (!agent || !agent.version?.history?.length) return null
    const historyItem = agent.version.history.find((item) => item.id === snapshotId)
    if (!historyItem) return null
    const restored = deepClone(historyItem.snapshot)
    restored.updatedAt = Date.now()
    return updateAgent(
      agentId,
      restored,
      {
        mergeStrategy: 'replace',
        note,
        type: 'restore'
      }
    )
  }

  const importAgents = (jsonString) => {
    try {
      const parsed = JSON.parse(jsonString)
      if (!Array.isArray(parsed)) {
        throw new Error('导入数据格式应为数组')
      }
      const sanitized = parsed.map((item) => {
        const base = createBlankAgent(item)
        base.id = generateId()
        base.createdAt = Date.now()
        base.updatedAt = Date.now()
        base.status = item.status ?? 'draft'
        base.version = {
          current: 1,
          published: base.status === 'published' ? 1 : 0,
          history: [createHistoryEntry(base, '导入', 'import')]
        }
        return base
      })
      agents.value = [...sanitized, ...agents.value]
      if (sanitized.length > 0) {
        activeAgentId.value = sanitized[0].id
      }
      persistState()
      syncActiveAgentToLegacySettings()
      return sanitized.length
    } catch (error) {
      console.error('[AgentStore] 导入智能体失败', error)
      throw error
    }
  }

  const exportAgents = (agentIds = null) => {
    const list = Array.isArray(agentIds) && agentIds.length > 0
      ? agents.value.filter((agent) => agentIds.includes(agent.id))
      : agents.value
    return JSON.stringify(list, null, 2)
  }

  watch(
    agents,
    () => {
      if (!initialized.value) return
      persistState()
      syncActiveAgentToLegacySettings()
    },
    { deep: true }
  )

  watch(
    activeAgentId,
    () => {
      if (!initialized.value) return
      persistState()
      syncActiveAgentToLegacySettings()
    }
  )

  return {
    agents,
    loading,
    activeAgentId,
    activeAgent,
    publishedAgents,
    draftAgents,
    initialize,
    selectAgent,
    createAgent,
    updateAgent,
    publishAgent,
    deleteAgent,
    cloneAgent,
    upsertCapabilityOption,
    registerVersionSnapshot,
    restoreVersion,
    importAgents,
    exportAgents
  }
})

